package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.vo.LoginVo;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        // 登录返回用户数据
        LoginVo loginVo = new LoginVo();
        // 游客登录
        if (phone == null && password == null) {
            String token = AppJwtUtil.getToken(0L);
            loginVo.setToken(token);
            return ResponseResult.okResult(loginVo);
        }
        // 用户登录
        if (phone != null && password != null) {
            LambdaQueryWrapper<ApUser> wrappres = Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, phone);
            ApUser apUser = apUserMapper.selectOne(wrappres);
            if (ObjectUtil.isEmpty(apUser)) {
                return ResponseResult.errorResult(1002, "用户不存在");
            }
            // 密码校验(加密)
//            if (password.equals(apUser.getPassword())) {
//                String token = AppJwtUtil.getToken(apUser.getId().longValue());
//                loginVo.setToken(token);
//                loginVo.setUser(apUser);
//                return ResponseResult.okResult(loginVo);
//            } else {
//                return ResponseResult.errorResult(1003, "密码错误");
//            }
        }
        return ResponseResult.okResult(null);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
